package sg.edu.nus.comp.icreate.ivletalk.forum;

import java.util.Calendar;
import java.util.GregorianCalendar;
import org.xmlpull.v1.XmlPullParser;

import android.util.Log;

public class ForumThreadXmlParser extends ForumXmlParser {
	private ForumThread rootThread = new ForumThread(null);

	@Override
	public Object getResult() {
		ForumThread currentThread = rootThread;
		int eventType;
		try {
			goToTag(TAG_THREAD, XmlPullParser.START_TAG);
			do {
				eventType = parser.getEventType();
				if (eventType == XmlPullParser.START_TAG && TAG_ID.equals(parser.getName())) {
					parser.next();
					currentThread.setId(parser.getText());
				} else if (eventType == XmlPullParser.START_TAG && TAG_THREAD.equals(parser.getName())) {
					ForumThread temp = new ForumThread(currentThread);
					currentThread.getReplies().add(temp);
					currentThread = temp;
				} else if (eventType == XmlPullParser.START_TAG && TAG_NUM_REPLIES.equals(parser.getName())) {
					parser.next();
					currentThread.setNumReplies(Integer.parseInt(parser.getText()));
				} else if (eventType == XmlPullParser.START_TAG && TAG_POST_BODY.equals(parser.getName())) {
					parser.next();
					currentThread.setBody(parser.getText());
				} else if (eventType == XmlPullParser.START_TAG && TAG_POST_TITLE.equals(parser.getName())) {
					parser.next();
					currentThread.setTitle(parser.getText());
				} else if (eventType == XmlPullParser.START_TAG && TAG_DATE.equals(parser.getName())) {
					parser.next();
					String dates[] = parser.getText().split("T");
					String date[] = dates[0].split("-");
					String time[] = dates[1].split(":");
					Calendar calendar = new GregorianCalendar(Integer.parseInt(date[0]), Integer.parseInt(date[1]), Integer.parseInt(date[2]),
							Integer.parseInt(time[0]), Integer.parseInt(time[1]));
					currentThread.setDate(calendar);
				} else if (eventType == XmlPullParser.START_TAG && TAG_POSTER.equals(parser.getName())) {
					parser.next();
					currentThread.setPoster(parser.getText());
				} else if (eventType == XmlPullParser.END_TAG && TAG_THREAD.equals(parser.getName())) {
					currentThread = currentThread.getParent();
				}
				parser.next();
			} while (parser.getEventType() != XmlPullParser.END_TAG || !TAG_RESULT.equals(parser.getName()));

		} catch (Exception e) {
			Log.e("error", "Error in parse xml", e);
		}
		return rootThread;
	}

}
